package com.huangbiao.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;


public class ShiroService implements IShiroService{

	private ShiroDAO shiroDAO;

	

	/**
	 * @param shiroDAO the shiroDAO to set
	 */
	public void setShiroDAO(ShiroDAO shiroDAO) {
		this.shiroDAO = shiroDAO;
	}

	/**
	 * 登录
	 */
	public void doLogin(String username, String password) throws Exception {
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			
			try {
				currentUser.login(token);// 执行登录
				token.setRememberMe(true);// 是否记住用户
			} catch (UnknownAccountException uae) {
				throw new Exception("账户不存在");
			} catch (IncorrectCredentialsException ice) {
				throw new Exception("密码不正确");
			} catch (LockedAccountException lae) {
				throw new Exception("用户被锁定了 ");
			} catch (AuthenticationException ae) {
				ae.printStackTrace();
				throw new Exception("未知错误");
			}
		}
	}

	/**
	 * 根据用户名查询密码
	 */
	public String getPasswordByUserName(String username) {
		try {
			return shiroDAO.getPasswordByUserName(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
		
	}

	/**
	 * 查询用户所有权限
	 */
	public List<String> getPermissionByUserName(String username) {
		return shiroDAO.getPermissionByUserName(username);
	}

	@Override
	public List<String> getRoleByUserName(String username) {
		return shiroDAO.getRoleByUserName(username); 
	}
	
	
	/**
	 * 注解测试
	 */
	@RequiresRoles(value = "admin")
	public String testRoles( ) {
		
		return "testRoles";
		
	}

}
